package com.resume.aipeople.controller;

import com.resume.aipeople.dto.*;
import com.resume.aipeople.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class UserController {
    
    private final UserService userService;
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<AuthResponse> register(@Valid @RequestBody RegisterRequest request) {
        try {
            log.info("收到用户注册请求: {}", request.getUsername());
            
            AuthResponse response = userService.register(request);
            
            if (response.isSuccess()) {
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("处理注册请求失败", e);
            AuthResponse errorResponse = new AuthResponse("系统错误，请稍后再试");
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<AuthResponse> login(@Valid @RequestBody LoginRequest request) {
        try {
            log.info("收到用户登录请求: {}", request.getUsernameOrEmail());
            
            AuthResponse response = userService.login(request);
            
            if (response.isSuccess()) {
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("处理登录请求失败", e);
            AuthResponse errorResponse = new AuthResponse("系统错误，请稍后再试");
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public ResponseEntity<UserDTO> getCurrentUser() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            
            return userService.findByUsername(username)
                    .map(user -> {
                        UserDTO dto = new UserDTO();
                        dto.setId(user.getId());
                        dto.setUsername(user.getUsername());
                        dto.setEmail(user.getEmail());
                        dto.setNickname(user.getNickname());
                        dto.setAvatarUrl(user.getAvatarUrl());
                        dto.setRole(user.getRole().name());
                        dto.setCreatedAt(user.getCreatedAt());
                        dto.setLastLoginAt(user.getLastLoginAt());
                        return ResponseEntity.ok(dto);
                    })
                    .orElse(ResponseEntity.notFound().build());
                    
        } catch (Exception e) {
            log.error("获取当前用户信息失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public ResponseEntity<String> logout() {
        try {
            // 清除SecurityContext中的认证信息
            SecurityContextHolder.clearContext();
            log.info("用户登出成功");
            return ResponseEntity.ok("登出成功");
        } catch (Exception e) {
            log.error("用户登出失败", e);
            return ResponseEntity.internalServerError().body("登出失败");
        }
    }
}
